package com.cssy.yd.logic.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.entity.BasicCompanyDO;
import com.cssy.yd.basic.entity.BasicCompanytypeDO;
import com.cssy.yd.basic.entity.BasicCurrencyDO;
import com.cssy.yd.basic.service.IBasicCompanyService;
import com.cssy.yd.basic.service.IBasicCompanyTypeService;
import com.cssy.yd.basic.service.IBasicCurrencyService;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoItemDO;
import com.cssy.yd.logic.entity.LogicQkDO;
import com.cssy.yd.logic.entity.LogicQkItemDO;
import com.cssy.yd.logic.service.ILogicPoItemService;
import com.cssy.yd.logic.service.ILogicPoService;
import com.cssy.yd.logic.service.ILogicQkItemService;
import com.cssy.yd.logic.service.ILogicQkService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtil;
import com.plat.util.DateUtils;
import com.plat.util.ExcelUtil;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.exception.SyCodeException;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Controller
@RequestMapping("/yd/logic/qk")
public class QkController extends BaseController<LogicQkDO> {
	private static final String MANAGER = "/yd/logic/qk/QkManager";// 列表页面
	private static final String EIDT = "/yd/logic/qk/QkOperation";// 添加、修改、显示页面
	private static final String EXCEL = "/views/printer/QkPrint.jsp";//每月请款页面
	@Resource(name = "logicQkService")
	private ILogicQkService logicQkService;
	
	@Resource(name = "logicQkItemService")
	private ILogicQkItemService logicQkItemService;
	

	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		 JqGridHandler hander=new JqGridHandler(request);
		 SearchConditions scs = new SearchConditions();
		 hander.getWheres(scs);
		 SearchResult result= logicQkService.findListByExample(scs);
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);

	}
	
	

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		 
		if (OperationFlag.ADD.equals(flag)) {// 我新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicQkDO lpd =logicQkService.findListById(id);
			SearchConditions scs = new SearchConditions();
			 scs.setRemovedProperty(null);//判断是否有删除标识
			scs.addCondition("qkid", lpd.getId(), SearchCondition.OP_EQUAL);
			List<LogicPoItemDO> itemlistDos=logicQkItemService.findListByExample(scs).getResults();
			model.addAttribute("qk", lpd);
			model.addAttribute("flag", "EDIT");
			model.addAttribute("qkitem", itemlistDos);
		}
		return EIDT;
	}
	

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicQkDO curAP, BindingResult result, Model model) throws SyBaseException, SyCodeException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("采购订单内容不能为空！");
			return bodyMap.modelMap;
		}try {
			logicQkService.qkSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	
	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicQkDO ld=logicQkService.findListById(field);
				if(ld!=null){
					ld.setRemoved(1);
					logicQkService.update(ld, SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}


	/**
	 * 导出单据详细信息
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException 
	
	@RequestMapping(value = "/exportExcel")
	public void exportExcel(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
		try{
			String id = request.getParameter("id");
			String gys=new String(request.getParameter("gys").getBytes("ISO-8859-1"), "UTF-8");
			List<LogicPoItemDO> lp=new ArrayList<LogicPoItemDO>();
			if(!"".equals(id)&&id!=null){
				lp = logicPoService.findItemListBypoId(id);
			}
			if(lp.size()>0){
				HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件
				HSSFSheet sheet = workbook.createSheet();// 创建一个Excel的Sheet
				HSSFRow row0 = sheet.createRow(0);
				// 设置行高
				row0.setHeight((short) 600);
				HSSFCell cell0 = row0.createCell(0);
				cell0.setCellValue("供应商:" + new String(request.getParameter("gys").getBytes("ISO-8859-1"), "GBK"));
				CellRangeAddress range = new CellRangeAddress(0, 0, 0, 7);
				sheet.addMergedRegion(range);
				// 第三行
				HSSFRow row1 = sheet.createRow(1);
				row1.setHeight((short) 500);
				HSSFCell cell = row1.createCell(0);
				cell.setCellValue(new HSSFRichTextString("物料类型"));
				cell = row1.createCell(1);
				cell.setCellValue(new HSSFRichTextString("材料名称"));
				cell = row1.createCell(2);
				cell.setCellValue(new HSSFRichTextString("材料编码"));
				cell = row1.createCell(3);
				cell.setCellValue(new HSSFRichTextString("型号"));
				cell = row1.createCell(4);
				cell.setCellValue(new HSSFRichTextString("单位"));
				cell = row1.createCell(5);
				cell.setCellValue(new HSSFRichTextString("部门"));
				cell = row1.createCell(6);
				cell.setCellValue(new HSSFRichTextString("采购数量"));
				cell = row1.createCell(7);
				cell.setCellValue(new HSSFRichTextString("采购单价"));
				cell = row1.createCell(8);
				cell.setCellValue(new HSSFRichTextString("采购币别"));
				cell = row1.createCell(9);
				cell.setCellValue(new HSSFRichTextString("采购汇率"));
				cell = row1.createCell(10);
				cell.setCellValue(new HSSFRichTextString("采购税率"));
				cell = row1.createCell(11);
				cell.setCellValue(new HSSFRichTextString("采购不含税单价"));
				cell = row1.createCell(12);
				cell.setCellValue(new HSSFRichTextString("采购含税金额"));
				cell = row1.createCell(13);
				cell.setCellValue(new HSSFRichTextString("采购不含税金额"));
				cell = row1.createCell(14);
				cell.setCellValue(new HSSFRichTextString("应付金额"));
				for(int i=0;i<lp.size();i++){
					HSSFRow row2 = sheet.createRow(i+2);
					row2.setHeight((short) 400);
					HSSFCell cell1 = row2.createCell(0);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getItmetype()));
					cell1 = row2.createCell(1);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getName()));
					cell1 = row2.createCell(2);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getCode()));
					cell1 = row2.createCell(3);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getSpec()));
					cell1 = row2.createCell(4);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getUnit()));
					cell1 = row2.createCell(5);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getDeptcode()));
					cell1 = row2.createCell(6);
					cell1.setCellValue(lp.get(i).getQuantity());
					cell1 = row2.createCell(7);
					cell1.setCellValue(lp.get(i).getPrice());
					cell1 = row2.createCell(8);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getCurrency()));
					cell1 = row2.createCell(9);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getExchangeRate()));
					cell1 = row2.createCell(10);
					cell1.setCellValue(new HSSFRichTextString(lp.get(i).getTaxRate()));
					cell1 = row2.createCell(11);
					cell1.setCellValue(lp.get(i).getStockPrice());
					cell1 = row2.createCell(12);
					cell1.setCellValue(lp.get(i).getQuantity()*lp.get(i).getPrice()*Integer.parseInt(lp.get(i).getExchangeRate()));
					cell1 = row2.createCell(13);
					cell1.setCellValue(lp.get(i).getQuantity()*lp.get(i).getStockPrice()*Integer.parseInt(lp.get(i).getExchangeRate()));
					cell1 = row2.createCell(14);
					cell1.setCellValue(lp.get(i).getQuantity()*lp.get(i).getPrice());
				}
				String fileNameDisplay = "采购申请单"
						+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				try {
					fileNameDisplay = new String(fileNameDisplay.getBytes("GBK"),
							"iso-8859-1");
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				fileNameDisplay = fileNameDisplay.replace(" ", "%20");
				response.addHeader("Content-Disposition", "attachment;filename="
						+ fileNameDisplay + ".xls");
			    response.setContentType("application/vnd.ms-excel"); 
			    OutputStream ouputStream = response.getOutputStream();  
			    workbook.write(ouputStream);  
			    ouputStream.flush();  
			    ouputStream.close();  
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	 */
	@RequestMapping("/output")
	public void output(HttpServletRequest request, HttpServletResponse response, Model model) throws SyBaseException, SyCodeException {
		String id = request.getParameter("id");
		LogicQkDO lpd =logicQkService.findListById(id);
		String qkrq = new SimpleDateFormat("yyyy-MM-dd").format(lpd.getQkrq());
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);//判断是否有删除标识
		scs.addCondition("qkid", lpd.getId(), SearchCondition.OP_EQUAL);
		List<LogicQkItemDO> itemlistDos=logicQkItemService.findListByExample(scs).getResults();
		Double quantitys = 0.0 ;
		Double zprices = 0.0 ;
		for(LogicQkItemDO logicQkItemDO : itemlistDos){
			if(logicQkItemDO.getQuantity() != null){
			quantitys += logicQkItemDO.getQuantity() ;
			if(logicQkItemDO.getPrice() != null){
				zprices += logicQkItemDO.getQuantity()*logicQkItemDO.getPrice();
				}
			}
		}
		request.setAttribute("quantitys", quantitys);
		request.setAttribute("zprices", zprices);
		request.setAttribute("qk", lpd);
		request.setAttribute("qkitem", itemlistDos);
		request.setAttribute("qkrq", qkrq);
		try {
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename=export_" + System.currentTimeMillis() + ".xls");
			request.getRequestDispatcher(EXCEL).forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
